package com.example.demo.controller;

import com.example.demo.domain.FileMsg;
import com.example.demo.dto.FileUploadDTO;
import com.example.demo.service.FileService;
import com.example.demo.util.FileUtil;
import com.example.demo.util.PageUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

@RestController
public class FileController {

    @Resource
    private FileService fileService;

    @Value("${path}")
    private String PATH;

    @PostMapping("/uploadFile")
    public String fileUpload(@RequestParam("file") MultipartFile file,
                             @RequestParam("username") String username
                             ,@RequestParam("time") String time){

        FileUploadDTO fileUploadDTO = new FileUploadDTO(file.getOriginalFilename());
        fileUploadDTO.setSource(file);
        fileUploadDTO.setUsername(username);
        fileUploadDTO.setUploadTime(time);
        Boolean flag = fileService.fileUpload(fileUploadDTO);
        if(flag) {
            return "上传成功！";
        }else{
            return "上传失败！";
        }
    }

    @GetMapping("/fileList/fileName")
    public List<FileMsg> getFileListByFileName(@RequestParam("fileName") String fileName){
        return fileService.queryFileListByFileName(fileName);
    }

    @GetMapping("/fileList")
    public List<FileMsg> getFileList(String orgid, Integer page,Integer limit) {
        return fileService.getFileList(orgid,PageUtil.start(page, limit), PageUtil.end(page, limit));
    }

    @GetMapping( "/download")
    public void downloadFile(String path, HttpServletRequest request, HttpServletResponse response) {
        String url = "F:\\Project\\预算管理_书吧\\yongyou\\src\\main\\resources\\file\\" +path;
        File file = new File(url);
        String fileName = path;
        FileUtil.downloadFile(fileName,file,response,request);
    }


    @GetMapping("/delFile")
    @ResponseBody
    public String deleteFile(String fileName){
        String path= PATH + fileName;
        File file=new File(path);
        boolean flag = fileService.deleteFile(file, fileName);
        //删除文件
        if(flag) {
            return "删除成功！";
        }else{
            return "删除失败！";
        }

    }
}
